package com.dashan.backend.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


public class XmlHelper {

    public static Document createXmlDocument(String rootName) {
        try {
            return DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().getDOMImplementation().createDocument(
                    null, rootName, null);
        } catch (DOMException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static Document string2Xml(String xmlString) {
        try {
            ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes());
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
            doc.getDocumentElement().normalize();
            return doc;
        } catch (SAXException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static String xml2String(Document xmlDoc) {
        try {
            
            ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
            DOMSource domSource = new DOMSource(xmlDoc);
            StreamResult streamResult = new StreamResult(baos);
            TransformerFactory tf = TransformerFactory.newInstance();
            tf.setAttribute("indent-number", new Integer(2));
            Transformer serializer;
            serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.transform(domSource, streamResult);
            
            
            return baos.toString();
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "Xml Serializer Error";
    }
}
